package com.example.internetplus.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.example.internetplus.controller.globalException.exception.LoginException;
import com.example.internetplus.utils.JwtUtils;
import com.example.internetplus.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {
    private final JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头的token
        String token = request.getHeader("auth");
        if (token == null){
            throw new LoginException("需要登录令牌",10111);
        }
        //解析token
        try {
            Long userId = jwtUtils.parseToken(token);
            //存入用户id
            UserContext.setUser(userId);
        }catch (Exception e){
            throw new LoginException("令牌问题",10111);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
